import time
from vnpy_ctastrategy.template import(
    CtaTemplate
)
from vnpy.trader.object import(
    BarData,
    TickData,
    TradeData,
    OrderData
)

from base import StopOrder
from vnpy.trader.constant import Status

from vnpy.trader.utility import(
    BarData,
    
)

# from vnpy.trader.utility import(
#     BarGenerator,
#     ArrayManager
# )
from typing import Any

class LiangCha(CtaTemplate):
    """"""

    author="LiangCha"

    direction=1
    go=1
    status=""
    oldPrice=0
    nowPrice=0

    myprice=0
    stopSunPrice=0
    stopYingPrice=0

    volCha=0
    volChaNow=0

    parameters=[  
        "go",
        "direction"
    ]

    variables=[
        "volChaNow",
        "myprice",
        "stopSunPrice",
        "stopYingPrice"
        
    ]

    def __init__(self, cta_engine: Any, strategy_name: str, vt_symbol: str, setting: dict) -> None:
        super().__init__(cta_engine, strategy_name, vt_symbol, setting)
        
        # self.huanjing="实盘"
        self.huanjing="实盘"
        self.bidPrice=0
        self.askPrice=0
        self.lastPrice=0

        self.orderid=""
        self.orderStatus=""
        self.stoporderid=""
        self.stoporderStatus=""
        self.vt_stoporderid=""
        self.vt_stoporderStatus=""
        self.limitorderid=""
        self.limitorderStatus=""
        self.status="等待中"
        self.lastStatus=""
        # self.msg=f",pos={self.pos},orderid={self.orderid},myprice={self.myprice}，stopSunPrice={self.stopSunPrice},stopYingPrice={self.stopYingPrice},volCha={self.volChaNow}"
        # self.bg = BarGenerator(self.on_bar)
        # self.am = ArrayManager()

    def on_init(self) -> None:
        self.write_log("市价LiangCha7 策略初始化")
        # self.load_bar(10)

    def on_start(self) -> None:
        self.pos=0
        self.lastStatus=""
        self.write_log("市价LiangCha 策略启动")
    
    def on_stop(self) -> None:
        # self.startTrade=0
        self.write_log("市价LiangCha 策略停止")

    def on_trade(self, trade: TradeData) -> None:
        self.myLog(f"on_order {trade.direction.value}{trade.offset.value},{trade.price},{trade.orderid}")
        self.myLog(f"********已成交******** {trade.direction.value}{trade.offset.value},{trade.price} ")
        return super().on_trade(trade)

    def on_stop_order(self, stop_order: StopOrder) -> None:
        return super().on_stop_order(stop_order)

    def on_order(self, order: OrderData) -> None:
        self.myLog(f"on_order {order.direction.value}{order.offset.value},{order.price},{order.status.value},{order.orderid}")
        if self.orderid.find(order.orderid)!=-1:
            self.orderStatus=order.status.value
            if order.status.value==Status.REJECTED.value:
                self.myLog("........已拒单........")
                self.status="等待中"
            elif order.status.value==Status.CANCELLED.value:
                self.myLog("........已撤单........")
                # self.direction=self.direction*-1
                self.status="等待中"
            elif order.status.value==Status.ALLTRADED.value:
                self.myLog(f"........已开仓,开止盈........")
                self.status="开止盈"
                # if self.direction==1:
                #     if self.bidPrice<self.myprice:
                #         # 滑点开仓 止损多1
                #         self.stopSunPrice=self.stopSunPrice-1
                #         print(f"........滑点买开止损多1........ mp={self.myprice} drc={self.direction} bp={self.bidPrice} ap={self.askPrice} sp={self.stopSunPrice} yp={self.stopYingPrice} id={self.orderid}")
                #     self.limitorderid=self.sell(self.stopYingPrice, 1)[0]
                # else:
                #     if self.askPrice>self.myprice:
                #         # 滑点开仓 止损多1
                #         self.stopSunPrice=self.stopSunPrice+1
                #         print(f"........滑点卖开止损多1........ mp={self.myprice} drc={self.direction} bp={self.bidPrice} ap={self.askPrice} sp={self.stopSunPrice} yp={self.stopYingPrice} id={self.orderid}")
                #     self.limitorderid=self.cover(self.stopYingPrice, 1)[0]
                # # TODO 止盈单挂单失败 需要特殊处理
        elif self.limitorderid.find(order.orderid)!=-1:
            self.limitorderStatus=order.status.value
            if order.status.value==Status.NOTTRADED.value:
                self.myLog("........已开盈........")
                self.status="波动中"
            elif order.status.value==Status.ALLTRADED.value:
                self.myLog("........已止盈,等待中........")
                self.go=0
                # self.direction=self.direction*-1
                self.status="等待中"
            elif order.status.value==Status.CANCELLED.value:
                self.myLog(f"........已撤盈,开止损........")
                self.status="开止损"
                if self.direction==1:
                    self.stoporderid=self.sell(self.stopSunPrice, 1)[0]
                else:
                    self.stoporderid=self.cover(self.stopSunPrice, 1)[0]
        elif self.stoporderid.find(order.orderid)!=-1:
            self.stoporderStatus=order.status.value
            if order.status.value==Status.ALLTRADED.value:
                self.myLog("........已止损,等待中........")
                # self.direction=0
                self.go=0
                self.status="等待中"
            elif order.status.value==Status.NOTTRADED.value or order.status.value==Status.SUBMITTING.value:
                self.myLog("........止损中........")
        return super().on_order(order)

    def on_tick(self, tick: TickData) -> None:
        # LiangCha.myLog(self,f"on tick={tick.last_price}")
        # self.tick=tick
        # self.nowPrice=tick.last_price
        # self.oldPrice=tick.last_price
        self.bidPrice=tick.bid_price_1
        self.askPrice=tick.ask_price_1
        
        # self.volChaNow=tick.bid_volume_1-tick.ask_volume_1
        if self.trading:
            if self.status=="等待中":
                self.myLog(f"等待中,监控参数={self.direction}")
                # self.lastStatus="等待中"
                if self.orderid:
                    self.orderid=""
                    self.orderStatus="等待中"
                    self.stoporderid=""
                    self.stoporderStatus="等待中"
                    self.vt_stoporderid=""
                    self.vt_stoporderStatus="等待中"
                    self.limitorderid=""
                    self.limitorderStatus="等待中"
                # if self.volChaNow<=self.volCha:
                # 计算开仓条件
                
                if self.direction!=0 and self.go:
                    self.status="开仓中"
                    # self.myLog("========开仓中========",tick=tick)
                    if self.huanjing=="测试":
                        if self.direction==1:
                            self.myprice=tick.ask_price_1
                            self.orderid=self.buy(self.myprice, 1)[0]
                            self.stopSunPrice=self.myprice-2
                            self.stopYingPrice=self.myprice+1
                        else:
                            self.myprice=tick.bid_price_1
                            self.orderid=self.short(self.myprice, 1)[0]
                            self.stopSunPrice=self.myprice+2
                            self.stopYingPrice=self.myprice-1
                    else:
                        if self.direction==1:
                            self.myprice=tick.bid_price_1
                            self.orderid=self.buy(self.myprice, 1)[0]
                            self.stopSunPrice=self.myprice-1
                            self.stopYingPrice=self.myprice+1
                        else:
                            self.myprice=tick.ask_price_1
                            self.orderid=self.short(self.myprice, 1)[0]
                            self.stopSunPrice=self.myprice+1
                            self.stopYingPrice=self.myprice-1
                    self.myLog(f"========开仓中========")
                else:
                    if self.lastStatus!="暂停中":
                        self.myLog("........暂停中........")
                        self.lastStatus="暂停中"
            elif self.status=="开仓中":
                # if self.myprice!=tick.ask_price_1:
                if self.huanjing=="测试":
                    if (self.direction==1 and self.myprice!=tick.ask_price_1) \
                        or (self.direction==-1 and self.myprice!=tick.bid_price_1) :
                        self.status="撤单中"
                        # self.myLog("撤单中",tick=tick)
                        self.myLog(f"........撤单中........")
                        self.cancel_order(self.orderid)
                        # TODO 极端情况 发送撤单的时候 已经成交 需要特殊处理
                    else:
                        if self.lastPrice!=tick.last_price:
                            self.myLog("........待开仓........")
                else:
                    if (self.direction==1 and self.myprice!=tick.bid_price_1) \
                        or (self.direction==-1 and self.myprice!=tick.ask_price_1) :
                        self.status="撤单中"
                        # self.myLog("撤单中",tick=tick)
                        self.myLog("........撤单中........")
                        self.cancel_order(self.orderid)
                        # TODO 极端情况 发送撤单的时候 已经成交 需要特殊处理
                    else:
                        self.myLog("........待开仓........")
            # elif self.status=="撤单中":
            #     self.myLog("撤单中") 
            elif self.status=="波动中":
                if (self.direction==1 and tick.bid_price_1<=self.stopSunPrice) \
                    or (self.direction==-1 and tick.ask_price_1>=self.stopSunPrice):
                    # self.myLog("已触损,撤止盈",tick=tick)
                    self.myLog("........已触损,撤止盈........")
                    self.cancel_order(self.limitorderid)
                else:
                    if self.lastPrice!=tick.last_price:
                        self.myLog(f"........波动中........")
            elif self.status=="开止盈":
                self.status="pending"
                if self.direction==1:
                    if self.bidPrice<self.myprice:
                        # 滑点开仓 止损多1
                        self.stopSunPrice=self.stopSunPrice-1
                        self.myLog(f"........滑点买开止损多1........")
                    self.limitorderid=self.sell(self.stopYingPrice, 1)[0]
                else:
                    if self.askPrice>self.myprice:
                        # 滑点开仓 止损多1
                        self.stopSunPrice=self.stopSunPrice+1
                        self.myLog(f"........滑点卖开止损多1........")
                    self.limitorderid=self.cover(self.stopYingPrice, 1)[0]
                # TODO 止盈单挂单失败 需要特殊处理
            else:
                # self.myLog(self.status,tick=tick)
                self.myLog("........pending........")
        self.lastPrice=tick.last_price

    def myLog(self,msg="") ->None:
        t=time.strftime('%H:%M:%S',time.localtime(time.time()))
        s=f"最新={self.lastPrice} 开价={self.myprice} 方向={self.direction} 买一={self.bidPrice} 卖一={self.askPrice} 止损={self.stopSunPrice} 止盈={self.stopYingPrice} id={self.orderid}"
        if msg:
            print(f"{t} {msg} {s}")
        else:
            print(f"{t} {s}")